package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author shangshang
 * @date 2024/11/26 19:56
 */
@Component
public class SearchReceiver {
    @Autowired
    private SearchService searchService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true", autoDelete = "false"),
            key = {MqConst.ROUTING_ALBUM_UPPER}))
    public void upperAlbum(Long albumId, Message message, Channel channel) {
        System.out.println("上架专辑：" + albumId);
        try {
            if (albumId != null) {
                searchService.upperAlbum(albumId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true", autoDelete = "false"),
            key = {MqConst.ROUTING_ALBUM_LOWER}))
    public void lowerAlbum(Long albumId, Message message, Channel channel) {
        System.out.println("下架专辑：" + albumId);
        try {
            if (albumId != null) {
                searchService.lowerAlbum(albumId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
